package com.huadao.cart_ccs.common;

import com.huadao.cart_ccs.common.threadControl.ThreadPoolProxyFactory;
import com.huadao.cart_ccs.data.bo.RawMessage;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class RawMessageManager {
    private static RawMessageManager ourInstance;
    private FileWriter fileWriter;
    //使用线程安全队列来缓存
    private Queue<RawMessage> cacheQueue = new ConcurrentLinkedQueue<>();
    private int maxCachedMessage=50;
    private int maxCachedTime=1000;
    private long writeMsgtime;

    public static RawMessageManager getInstance() {
        synchronized (RawMessageManager.class) {
            if (ourInstance == null) {
                ourInstance = new RawMessageManager();
            }
        }
        return ourInstance;
    }

    private RawMessageManager() {
        File file = new File(Constants.logDir, Constants.RawMessagefileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            fileWriter=new FileWriter(file, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void writeRawMessage(RawMessage rawMessage) {
        cacheQueue.add(rawMessage);
        if(writeMsgtime==0){
            writeMsgtime=System.currentTimeMillis();
        }
        long current=System.currentTimeMillis();
        if(cacheQueue.size()>=maxCachedMessage||current-writeMsgtime>=maxCachedTime){
            writeMessageIntoFile();
        }
    }

    private void writeMessageIntoFile() {
        writeMsgtime=0;
        final StringBuilder stringBuilder=new StringBuilder();
        while (!cacheQueue.isEmpty()){
            RawMessage rawMessage=cacheQueue.poll();
            stringBuilder.append(rawMessage.getShowLogMessage());
        }
        if(stringBuilder.length()>0){
            //为了提高效率，不使用锁，不关闭流，但是为了线程安全，请使用单线程操作
                ThreadPoolProxyFactory.getSingleThreadPoolProxy().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            writeFile(stringBuilder.toString());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
        }
    }

    private void writeFile(String msg) throws IOException {
        fileWriter.write(msg);
        fileWriter.flush();
//        fileWriter.close();
    }
}
